package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.Category;
import com.itheima.wisdomnext.entity.Post;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.mapper.CategoryMapper;
import com.itheima.wisdomnext.mapper.PostMapper;
import com.itheima.wisdomnext.service.CategoryService;
import com.itheima.wisdomnext.util.CategoryS_Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private PostMapper postMapper;

    @Override
    public List<Category> getAllCategories() {
        List<Category> all = categoryMapper.findAll();
        if (all == null) {
            CategoryS_Util.isTrue(true, ErrorCode.FAILED,"分类List查询失败");
        }
        return all;
    }

    @Override
    public Category getCategoryByName(String name) {
        Category byName = categoryMapper.findByName(name);
        if (byName == null) {
            CategoryS_Util.isTrue(true,ErrorCode.FAILED,"分类查询失败");
        }
        return byName;
    }

    @Override
    public void addCategory(String name) {
        if (categoryMapper.existsByName(name) > 0) {
            CategoryS_Util.isTrue(true,ErrorCode.FAILED,"该分类名称已存在");
        }
        Category category = new Category(name);
        categoryMapper.insert(category);
    }

    @Override
    public void deleteCategory(int id) throws Exception{
        categoryMapper.deleteById(id);
    }

    @Override
    public void updateCategory(Category category) {
        int i = categoryMapper.update(category);
        if (i < 0) {
            CategoryS_Util.isTrue(true,ErrorCode.FAILED,"更新分类失败");
        }
    }

    // 根据分类名称获取该分类下的所有帖子
    @Override
    public List<Post> getPostsByCategory(String categoryName) {
        // 获取分类对象
        Category category = categoryMapper.findByName(categoryName);
        if (category != null) {
            // 使用 PostMapper 获取该分类下的所有帖子
            return postMapper.findByCategoryId(category.getId());
        }else {
            CategoryS_Util.isTrue(true,ErrorCode.FAILED,"获取该分类下的所有帖子失败");
            return null;
        }
    }
}
